package com.joolun.web.controller.common;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.joolun.common.annotation.Anonymous;
import com.joolun.common.core.controller.BaseController;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.utils.StringUtils;
import com.joolun.common.utils.ip.IpUtils;
import com.joolun.system.domain.ScrmChannelStatistics;
import com.joolun.system.domain.ScrmCustomerInfo;
import com.joolun.system.domain.dto.SuggestionDto;
import com.joolun.system.domain.dto.WxLoginDto;
import com.joolun.weixin.config.WxMaConfiguration;
import com.joolun.weixin.service.IScrmChannelRecordLogService;
import com.joolun.weixin.service.IScrmChannelStatisticsService;
import com.joolun.weixin.service.IScrmCustomerInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * APP登录授权
 *
 * @author 李鹏军
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/auth")
public class AppLoginController extends BaseController {


    @Autowired
    private  WxMpService wxMpService;


    @Autowired
    private IScrmCustomerInfoService iScrmCustomerInfoService;

    private final IScrmChannelStatisticsService scrmChannelStatisticsService;

    private final IScrmChannelRecordLogService scrmChannelRecordLogService;

    /**
     * 微信小程序手机号码授权登录
     * @param input
     */
    private static final String APPID = "wx6dc2f5d77b3bfabf";
    private static final String SECRET = "9eaf2ad64bbd67ef960ce63fb63b0937";
    @PostMapping("/forword")
    @Anonymous
    @Operation(summary = "小程序跳转", description = "wx.login()每次返回的code只能使用一次")
    public AjaxResult login(@Validated @RequestBody WxLoginDto wxLoginDto) {
        log.info("小程序登录：{}",JSONObject.toJSONString(wxLoginDto));
        String code = wxLoginDto.getCode();

        String openId = wxLoginDto.getOpenId();
        String extCorpId = "ww83094d8ad34b9aa8";

        if(StringUtils.isBlank(openId)){
            return AjaxResult.error("openid异常");
        }
        // 首先获取最新的token信息
        String tokenParam = "appid=" + APPID + "&secret=" + SECRET + "&grant_type=client_credential";
        String tokenResult = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?"+tokenParam);
        log.info("----tokenResult:{}",tokenResult);

        JSONObject tokenJSONObject = JSONObject.parseObject(tokenResult);

        String accessToken = tokenJSONObject.getString("access_token");
        // 通过登录信息获取用户的手机号码

        log.info("----code:{},accessToken:{}",code,accessToken);
        // 获取token 信息
        String body = "{\"code\": \"" + code + "\"}";

        Map<String,String> map =new HashMap<>();
        String result = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken,body);

       // String result = "{\"errcode\":0,\"errmsg\":\"ok\",\"phone_info\":{\"phoneNumber\":\"15927699440\",\"purePhoneNumber\":\"15927699440\",\"countryCode\":\"86\",\"watermark\":{\"timestamp\":1737712227,\"appid\":\"wxc33aa3a3272176a1\"}}}\n";
        JSONObject jsonString = JSONObject.parseObject(result);
        log.info("----获取微信手机号返回：{}",jsonString);
        //----获取微信手机号返回：{"errcode":0,"errmsg":"ok","phone_info":{"phoneNumber":"15927699440","purePhoneNumber":"15927699440","countryCode":"86","watermark":{"timestamp":1737712227,"appid":"wxc33aa3a3272176a1"}}}

        int returnCode = jsonString.getInteger("errcode");
        if(returnCode != 0){
            // 获取微信手机号失败
            return AjaxResult.error("获取微信手机号异常");
        }
        String phoneInfo = jsonString.getString("phone_info");
        String purePhoneNumber = JSONObject.parseObject(phoneInfo).getString("purePhoneNumber");

        ScrmCustomerInfo  scrmCustomerInfo = iScrmCustomerInfoService.getOne(Wrappers.lambdaQuery(ScrmCustomerInfo.class).eq(ScrmCustomerInfo::getOpenId,openId)
                .isNull(ScrmCustomerInfo::getExtCustomerId));
        scrmCustomerInfo.setPhoneNumber(purePhoneNumber);
        scrmCustomerInfo.setLzTime(new Date());
        iScrmCustomerInfoService.saveOrUpdate(scrmCustomerInfo);

        // 更新统计数据
        ScrmChannelStatistics scrmChannelStatistics = scrmChannelStatisticsService.getOne(Wrappers.lambdaQuery(ScrmChannelStatistics.class).eq(ScrmChannelStatistics::getPlanId,wxLoginDto.getPlanId()));
        if(scrmChannelStatistics != null){
            scrmChannelStatistics.setLzNum(scrmChannelStatistics.getLzNum()+1);
            scrmChannelStatisticsService.saveOrUpdate(scrmChannelStatistics);
        }
        // 添加行为记录-留资
        scrmChannelRecordLogService.add(wxLoginDto.getPlanId(),"",extCorpId,"LiuZi");
        return AjaxResult.success(purePhoneNumber);

    }

    /**
     * 创建调用jsapi时所需要的签名
     *
     * @param url url
     * @return RestResponse
     */
    @GetMapping("/createJsapiSignature/{appid}")
    @Anonymous
    @Operation(summary = "创建调用jsapi时所需要的签名", description = "创建调用jsapi时所需要的签名",
            parameters = {@Parameter(required = true, in = ParameterIn.QUERY, name = "url", description = "url", example = "https://fly2you.cn")}
    )
    public AjaxResult<WxJsapiSignature> createJsapiSignature(@PathVariable String appid, @RequestParam String url) {
        WxJsapiSignature data = null;
        try {
            data = wxMpService.switchoverTo(appid).createJsapiSignature(url);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return AjaxResult.success(data);
    }

    /**
     * code静默登录
     *
     * @param wxLoginDto code
     * @return RestResponse
     */
    @Anonymous
    @PostMapping("/loginByCode")
    public AjaxResult loginByCode(@RequestBody WxLoginDto wxLoginDto ) {
        String code =wxLoginDto.getCode();
        Long planId = wxLoginDto.getPlanId();

        String extCorpId = "ww83094d8ad34b9aa8";
        Map<String,Object> map = new HashMap<>();
        try {
            WxMaJscode2SessionResult session = WxMaConfiguration.getMaService(APPID).jsCode2SessionInfo(code);

          // WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            log.info("------获取openid：{},---投放计划ID:{}",JSONObject.toJSONString(session),planId);
            String openId = session.getOpenid();
            String unionid = session.getUnionid();

            String phone = wxLoginDto.getPhoneNumber();
            // H5不留资
            if(StringUtils.isEmpty(phone) || phone.equals("0")){
                // 根据openid查询用户信息是否已经留资
                ScrmCustomerInfo scrmCustomerInfo = iScrmCustomerInfoService.getOne(Wrappers.lambdaQuery(ScrmCustomerInfo.class).eq(ScrmCustomerInfo::getOpenId,openId)
                        .isNull(ScrmCustomerInfo::getExtCustomerId));
                if (Objects.isNull(scrmCustomerInfo)) {
                    // 用户不存在，新增用户
                    scrmCustomerInfo = new ScrmCustomerInfo();
                    scrmCustomerInfo.setUnionId(unionid);
                    //scrmCustomerInfo.setExtCustomerId(openId);
                    scrmCustomerInfo.setPlanId(planId);
                    scrmCustomerInfo.setFollowStatus("1");
                    scrmCustomerInfo.setOpenId(openId);
                    String ip =IpUtils.getIpAddr();
                    scrmCustomerInfo.setIp(ip);
                    scrmCustomerInfo.setAddress(IpUtils.getCityInfoByMemorySearch(ip));
                    // TODO: 企业ID传值
                    scrmCustomerInfo.setExtCorpId(extCorpId);
                    scrmCustomerInfo.setCreateTime(new Date());
                    iScrmCustomerInfoService.save(scrmCustomerInfo);
                    map.put("isRetention",false);
                    // 更新uv统计
                    ScrmChannelStatistics scrmChannelStatistics = scrmChannelStatisticsService.getOne(Wrappers.lambdaQuery(ScrmChannelStatistics.class).eq(ScrmChannelStatistics::getPlanId,planId));
                    if(scrmChannelStatistics != null){
                        scrmChannelStatistics.setUvNum(scrmChannelStatistics.getUvNum() +1);
                        scrmChannelStatistics.setUpdateTime(new Date());
                        scrmChannelStatisticsService.saveOrUpdate(scrmChannelStatistics);
                    }
                    // 添加行为记录-UV
                    scrmChannelRecordLogService.add(planId,"",extCorpId,"UV");

                }else{
                    map.put("isRetention",false);
                    scrmCustomerInfo.setUpdatedAt(new Date());
                    if(StringUtils.isNotEmpty(scrmCustomerInfo.getPhoneNumber())){
                        map.put("isRetention",true);
                    }
                    String ip = IpUtils.getIpAddr();
                    scrmCustomerInfo.setIp(ip);
                    scrmCustomerInfo.setAddress(IpUtils.getCityInfoByMemorySearch(ip));
                    iScrmCustomerInfoService.saveOrUpdate(scrmCustomerInfo);
                }
                map.put("tempUserId",scrmCustomerInfo.getId());
                map.put("userId",scrmCustomerInfo.getId());
            }else{
                // h5留资
                ScrmCustomerInfo scrmCustomerInfo = iScrmCustomerInfoService.getOne(Wrappers.lambdaQuery(ScrmCustomerInfo.class).eq(ScrmCustomerInfo::getPhoneNumber,phone));
                //scrmCustomerInfo.setExtCustomerId(openId);
                scrmCustomerInfo.setUnionId(unionid);
                scrmCustomerInfo.setOpenId(openId);
                scrmCustomerInfo.setUpdateTime(new Date());
                scrmCustomerInfo.setFollowStatus("1");
                if(StringUtils.isEmpty(scrmCustomerInfo.getIp())){
                    String ip = IpUtils.getIpAddr();
                    scrmCustomerInfo.setIp(ip);
                    scrmCustomerInfo.setAddress(IpUtils.getCityInfoByMemorySearch(ip));
                }
                iScrmCustomerInfoService.saveOrUpdate(scrmCustomerInfo);
                map.put("isRetention",true);
                map.put("tempUserId",scrmCustomerInfo.getId());

                // 更新统计数据
                ScrmChannelStatistics scrmChannelStatistics = scrmChannelStatisticsService.getOne(Wrappers.lambdaQuery(ScrmChannelStatistics.class).eq(ScrmChannelStatistics::getPlanId,planId));
                if(scrmChannelStatistics != null){
                    scrmChannelStatistics.setLzNum(scrmChannelStatistics.getLzNum()+1);
                    scrmChannelStatisticsService.saveOrUpdate(scrmChannelStatistics);
                }
                map.put("userId",scrmCustomerInfo.getId());

            }
            map.put("openId",openId);
        } catch (WxErrorException e) {
            log.error("登录失败", e);
            return AjaxResult.error("登录失败：" + e.getError().getErrorMsg());
        }
        return AjaxResult.success("",map);
    }


    @PostMapping("/suggestion")
    @Operation(summary = "提交建议", description = "提交建议")
    public AjaxResult suggestion(@RequestBody SuggestionDto suggestionDto) {

        return AjaxResult.success();

    }
}
